package cn.com.xy.sms.sdk.queue;

import org.json.JSONObject;

import cn.com.xy.sms.sdk.constant.Constant;
import cn.com.xy.sms.sdk.db.entity.EmergencyManger;
import cn.com.xy.sms.sdk.log.LogManager;
import cn.com.xy.sms.sdk.net.util.EmergencyActionUtil;



public class EmergencyQueue extends Thread{

	 static boolean isRun = false;

	    public synchronized static void runEmergencyQueue() {
	        /*ONEPLUS-1607 songzhirong 20161022 start*/
	    	if (System.currentTimeMillis() >= (Constant.lastEmergencyUpdateTime + Constant.emergencyTimeCyc)) {
	    		  if (isRun == false ) {
	  				isRun = true;
	  	            // 当队列线程序未运行时,才运行
	  	        	EmergencyQueue queue = new EmergencyQueue();
	  	            queue.start();
	  	        }
	    		Constant.lastEmergencyUpdateTime = System.currentTimeMillis();
	    	}
	        /*ONEPLUS-1607 songzhirong 20161022 end*/

	    }
	    
	    @Override
	    public void run() {
	        try {
	            this.setName("xiaoyuan_EmergencyQueue");
	            android.os.Process
	                    .setThreadPriority(SdkTaskQueue.XIAOYUAN_THREA_PRIORITY);
	                try {
	                    Thread.sleep(1000);
	                  
	                    JSONObject emergency = EmergencyManger.queryNextEmergency();
	                    handleEmergency(emergency);
	                 

	                } catch (Throwable e) {
	                    // TODO: handle Throwable
	                }
	                isRun = false;
	        } catch (Throwable e) {
//	            e.printStackTrace();
                LogManager.e(Constant.TAG, "run: ", e);

	        }finally{
	        	 isRun = false;
	        }

	    }
	  
	    private void handleEmergency(JSONObject emergency) {
	       
	        if (emergency != null) {
	            try {	              
	            	EmergencyActionUtil.doEmAction(emergency.optString("emContent"));
	            	EmergencyManger.deleteEmergency(emergency);
	            } catch (Throwable e) {
//	                e.printStackTrace();
	                LogManager.e(Constant.TAG, "handleEmergency: ", e);

	            } finally {
	                try {
	                    Thread.sleep(2000);
	                } catch (Throwable e) {
//	                    e.printStackTrace();
		                LogManager.e(Constant.TAG, "handleEmergency: ", e);

	                }
	                handleEmergency(EmergencyManger.queryNextEmergency());
	            }
	        } else {
	            isRun = false;
	        }
	    }

}
